/**
 * @description ajax
 * @author flower.cheng
 */
import axios from 'axios'
import qs from 'qs'
import { PHPAPI } from '@/service/apiConfig'
import userAuth from '@/service/userAuth'
import BoqiiAuth from '@/assets/lib/boqii-node-auth'
let auth = new BoqiiAuth()

function delEmpty(input) {
  let str = {}
  const parakeys = Object.keys(input)
  for (let i = 0; i < parakeys.length; i++) {
    if (
      (input[parakeys[i]] != '' && input[parakeys[i]] != undefined) ||
      input[parakeys[i]] === 0 ||
      input[parakeys[i]] === false
    ) {
      str[parakeys[i]] = input[parakeys[i]]
    }
  }
  return str
}
const pageApi = {}
class HttpService {
  constructor() {
    this.headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  }
  nodeCall(apiObj, data = {}) {
    let url = apiObj.url || ''
    let method = apiObj.method || ''
    let pathParams = data
    data.SystemName = 'webapp'

    let initPar = {}
    if (!url || !method) {
      console.error('请求缺少url 或者method,请求出错！！！！')
    }
    if (method === 'get') {
      Object.keys(pathParams).forEach(key => {
        if (url.indexOf(':' + key) > -1) {
          url = url.replace(':' + key, pathParams[key])
          delete pathParams[key]
        }
      })
      // 将剩余参数拼接到url，防止get请求额外的参数无法通过body传递不到后端，通过url传递
      url = url + '?' + qs.stringify(pathParams)
    }
    initPar = Object.assign(initPar, data)
    let headers = {
      Authorization: initPar.UserId || '',
      Sign: auth.signParams(delEmpty(initPar), 'weapp'),
      'Vary-Client': 'weapp'
    }
    return new Promise((resolve, reject) => {
      let options = {
        headers: Object.assign({}, this.headers, headers),
        withCredentials: false,
        timeout: 15000
      }
      let instance = axios.create(options)
      console.log('------initPar------', initPar)
      instance[method](url, qs.stringify(initPar))
        .then(
          function(res) {
            console.log('=======res', res)
            if (res.data.ResponseStatus !== 0) {
              // alert(res.data.ResponseMsg)
              reject(res.data)
            }
            resolve(res.data)
          },
          function(err) {
            console.log('============', err)
            reject(err)
            if (err.response) {
              console.log('-----err.ResponseData----:', err.response.data)
            }
          }
        )
        .catch(function(err) {
          console.log('-------------ajax catch:', err)
        })
    })
  }
  call(apiObj, data = {}) {
    console.log('apiObj', apiObj)
    let url = apiObj.url || ''
    let method = apiObj.method || ''
    let pathParams = data.params || ''
    let initPar = {}
    let key = `${url}.${method}`
    let isSelfHandler = false
    if (data.isSelf) {
      isSelfHandler = data.isSelf
      delete data.isSelf
    }
    // if (pageApi[url + method]) {
    //     return new Promise((resolve, reject) => {
    //         reject();
    //     })
    // }
    pageApi[url + method] = 1
    if (!url || !method) {
      console.error('请求缺少url 或者method,请求出错！！！！')
    }
    if (pathParams) {
      Object.keys(pathParams).forEach(key => {
        if (url.indexOf(':' + key) > -1) {
          url = url.replace(':' + key, pathParams[key])
          delete pathParams[key]
        }
      })
      // 将剩余参数拼接到url，防止get请求额外的参数无法通过body传递不到后端，通过url传递
      url = url + '?' + qs.stringify(pathParams)
      delete data.params
    }
    data.domain = window.location.origin
    data.UDID = new Date().getTime()
    data.SystemName = userAuth.getUserAuth().SystemName || 'H5'
    initPar = Object.assign(initPar, data)
    initPar.Act = url
    if (userAuth.getUserId()) {
      initPar.UserId = userAuth.getUserId()
      // initPar.Uid = userAuth.getUid()
      initPar.UDID = userAuth.getUserAuth().UDID || new Date().getTime()
    }
    return new Promise((resolve, reject) => {
      let options = {
        // baseURL: 'https://some-domain.com/api/',
        headers: this.headers,
        withCredentials: false,
        timeout: 15000
      }
      let instance = axios.create(options)
      instance[method](PHPAPI, qs.stringify(initPar))
        .then(
          function(res) {
            delete pageApi[url + method]
            if (res.data.ResponseStatus !== 0) {
              if (isSelfHandler) {
                reject(res.data)
              } else {
                if (
                  res.data.ResponseStatus == 422 ||
                  res.data.ResponseStatus == 500 ||
                  res.data.ResponseStatus === -1 ||
                  res.data.ResponseStatus === 10001 ||
                  res.data.ResponseStatus === 1000
                ) {
                  // 如果刚开始请求就错误此时没有$vueInstance
                  // $vueInstance.$toast({
                  //   message: res.data.ResponseMsg,
                  //   duration: 1500
                  // });
                  Vue.$toast({
                    message: res.data.ResponseMsg,
                    duration: 1500
                  })
                }
                reject(res.data)
              }
            } else {
              resolve(res.data)
            }
          },
          function(err) {
            console.log('============', err)
            delete pageApi[url + method]
            // deleteRequestQueen(key)
            reject(err)
            if (err.response) {
              console.log('-----err.ResponseData----:', err.response.data)
            }
          }
        )
        .catch(function(err) {
          // deleteRequestQueen(key)
          console.log('-------------ajax catch:', err)
        })
    })
  }
}

export default new HttpService()
